package com.mask.sca.auth.granter;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Map;

public class SmsCodeTokenGranter extends AbstractTokenGranter {
    private static final String GRANT_TYPE = "sms_code";
    private final AuthenticationManager authenticationManager;
    private final StringRedisTemplate redisTemplate;

    public SmsCodeTokenGranter(AuthenticationManager authenticationManager,
                               AuthorizationServerTokenServices tokenServices,
                               ClientDetailsService clientDetailsService,
                               OAuth2RequestFactory requestFactory,
                               StringRedisTemplate redisTemplate) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> params = tokenRequest.getRequestParameters();
        String phone = params.get("phone");
        String code = params.get("code");
        if (phone == null || code == null) {
            throw new InvalidGrantException("手机号和验证码不能为空");
        }
        if (!phone.matches("^1[3-9]\\d{9}$")) {
            throw new InvalidGrantException("手机号格式不正确");
        }
        String cacheCode = redisTemplate.opsForValue().get("sms:code:" + phone);
        if (cacheCode == null || !cacheCode.equals(code)) {
            throw new InvalidGrantException("验证码错误或已过期");
        }
        // 验证通过后可清除验证码
        redisTemplate.delete("sms:code:" + phone);
        // 这里可根据手机号查找用户并认证
        Authentication userAuth = new org.springframework.security.authentication.UsernamePasswordAuthenticationToken(phone, code);
        userAuth = authenticationManager.authenticate(userAuth);
        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("手机号认证失败");
        }
        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return getTokenServices().createAccessToken(new OAuth2Authentication(storedOAuth2Request, userAuth));
    }
} 